//index.js
let formatTime = require('../../utils/util.js')
let WxParse = require('../../wxParse/wxParse.js')

let app = getApp()
Page({
  data: {
    autoplay: true,
    intervalTime: 3000,
    duration: 1000,
    goodsDetail:{},
    swiperCurrent: 0,  
    hasMoreSelect:false,
    selectSize:"",
    selectSizePrice: 0.00,
    selectSizePriceOld: 0.00,
    shopNum: 0,
    hideShopPopup:true,
    ifSecKill: false,
    buyNumber:0,
    buyNumMin: 1,
    buyNumMax: 100,
    categories: [{ id: 4653, name: "商品介绍" }, { id: 4669, name: "评价" }],
    activeCategoryId: 4653,
    propertyChildIds:"",
    propertyChildNames:"",
    canSubmit:false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo:{},
    shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
    ids:'',
    time: {},
    restTime: {day: '0', hour: '00', minute: '00', second: '00'},
    commentListFilter: [],
    commentList: [],
    commentPercent: 98,
    commentTotal: 222,
    id: '',
    introduction: '',
    interval: '',
    type: 0
  },

  //事件处理函数
  swiperchange: function(e) {
      //console.log(e.detail.current)
       this.setData({  
        swiperCurrent: e.detail.current  
    })  
  },
  onLoad: function (e) {
    if (e) {
      this.setData({
        id: e.id
      })

      if (e.inviter_id) {
        wx.setStorage({
          key: 'inviter_id_' + e.id,
          data: e.inviter_id
        })
      }

      // if (e.type == 1) {
      //   let that = this
      //   this.setData({
      //     ifSecKill: true,
      //     type: e.type,
      //     endTime: JSON.parse(e.endtime)
      //   })

      //   that.data.interval = setInterval(function () {
      //     let endDate = new Date(formatTime.formatTime(new Date(that.data.endTime)))
      //     let restTimeTemp = formatTime.restTime(new Date(), endDate)

      //     //console.log(restTime)
      //     that.setData({
      //       restTime: restTimeTemp
      //     })

      //   }, 1000)

      // }

    }
  
    this.getDetails(this.data.id)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this
    clearInterval(that.data.interval)
  },

  onShow() {
    this.getCartNum()
  },	

  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  toAddShopCar: function () {
    if (this.data.type != 2) {
      this.setData({
        shopType: "addShopCar"
      })
      this.bindGuiGeTap()
    }
   
  },
  tobuy: function () {
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
    /*    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
          this.bindGuiGeTap();
          return;
        }
        if(this.data.buyNumber < 1){
          wx.showModal({
            title: '提示',
            content: '暂时缺货哦~',
            showCancel:false
          })
          return;
        }
        this.addShopCar();
        this.goShopCar();*/
  },  
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
     this.setData({  
        hideShopPopup: false 
    })  
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
     this.setData({  
        hideShopPopup: true 
    })  
  },
  numJianTap: function() {
     if(this.data.buyNumber > this.data.buyNumMin){
        var currentNum = this.data.buyNumber;
        currentNum--; 
        this.setData({  
            buyNumber: currentNum
        })  
     }
  },
  numJiaTap: function() {
     if(this.data.buyNumber < this.data.buyNumMax){
        var currentNum = this.data.buyNumber;
        currentNum++ ;
        this.setData({  
            buyNumber: currentNum
        })  
     }
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.goodsDetail.sku_list[e.currentTarget.dataset.propertyindex].sub;
    for(var i = 0;i < childs.length;i++){
      that.data.goodsDetail.sku_list[e.currentTarget.dataset.propertyindex].sub[i].active = false;
    }
    // 设置当前选中状态
    that.data.goodsDetail.sku_list[e.currentTarget.dataset.propertyindex].sub[e.currentTarget.dataset.propertychildindex].active = true;
    // 获取所有的选中规格尺寸数据
    var needSelectNum = that.data.goodsDetail.sku_list.length;
    var curSelectNum = 0;
    var propertyChildIds= "";
    var propertyChildNames = "";
    for (var i = 0; i < that.data.goodsDetail.sku_list.length;i++) {
      childs = that.data.goodsDetail.sku_list[i].sub;
      for (var j = 0;j < childs.length;j++) {
        if(childs[j].active){
          curSelectNum++;
          propertyChildIds = propertyChildIds + that.data.goodsDetail.sku_list[i].id + ':' +childs[j].id +",";
          propertyChildNames = propertyChildNames + that.data.goodsDetail.sku_list[i].name + ":"+ childs[j].name +"  ";
        }
      }
    }
    //console.log('ids:' + propertyChildIds)
    let skuIDList = this.data.goodsDetail.sku.split(',')
    let skuIDPair = ''
    for (var i = 0; i < skuIDList.length; i++) {
      let skuIDSubList = propertyChildIds.split(',')
      for (var j = 0; j < skuIDSubList.length; j++) {
        if (skuIDSubList[j].split(':')[0] == skuIDList[i])
          skuIDPair = skuIDPair + '-' + skuIDSubList[j].split(':')[1] 
      }
    }

    console.log('ids:' + skuIDPair.slice(1))
    this.setData({
      ids: skuIDPair.slice(1)
    })

    for (var i = 0; i < this.data.goodsDetail.product_sku.length; i++) {
      if (this.data.goodsDetail.product_sku[i].ids == skuIDPair.slice(1)) {
        this.setData({
          selectSizePrice: this.data.goodsDetail.product_sku[i].price.toFixed(2),
          selectSizePriceOld: this.data.goodsDetail.product_sku[i].old_price.toFixed(2)
        })
      }
    }

    var canSubmit = false;
    if (needSelectNum == curSelectNum) {
      canSubmit = true;
    }
    // 计算当前价格
    if (canSubmit) {

      // wx.request({
      //   url: 'https://api.it120.cc/'+ app.globalData.subDomain +'/shop/goods/price',
      //   data: {
      //     goodsId: that.data.goodsDetail.basicInfo.id,
      //     propertyChildIds:propertyChildIds
      //   },
      //   success: function(res) {
      //     that.setData({
      //       selectSizePrice:res.data.data.price,
      //       propertyChildIds:propertyChildIds,
      //       propertyChildNames:propertyChildNames,
      //       buyNumMax:res.data.data.stores,
      //       buyNumber:(res.data.data.stores>0) ? 1: 0
      //     });
      //   }
      // })
    }

    
    this.setData({
      goodsDetail: that.data.goodsDetail,
      canSubmit:canSubmit
    })  
  },

  tabSourceClick: function (e) {
    this.setData({
      activeCategoryId: e.currentTarget.id
    });
    
  },

  /**
  * 加入购物车
  */
  addShopCar:function(){
    if (this.data.type != 2) {

      if (this.data.goodsDetail.sku_list && !this.data.canSubmit) {
        if (!this.data.canSubmit) {
          wx.showModal({
            title: '提示',
            content: '请选择商品规格！',
            showCancel: false
          })
        }
        this.bindGuiGeTap();
        return;
      }
      if (this.data.buyNumber < 1) {
        wx.showModal({
          title: '提示',
          content: '购买数量不能为0！',
          showCancel: false
        })
        return;
      }
      this.addToCart()

    }
  },
	/**
	  * 立即购买
	  */
  buyNow:function(){
    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      this.bindGuiGeTap();
      wx.showModal({
        title: '提示',
        content: '请先选择规格尺寸',
        showCancel:false
      })
      return;
    }    
    if(this.data.buyNumber < 1){
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel:false
      })
      return;
    }

   
    this.closePopupTap();

    wx.navigateTo({
      url: "/pages/to-pay-order/index?orderType=buyNow"
    })    
  },
  
  // onShareAppMessage: function () {
  //   // console.log('lalala2')
  //   app.shareMessage()
    
  // },

  /**
   * 获取商品详情
   */
  getDetails: function (id) {
    let token = wx.getStorageSync('token')
    let that = this
    if (wx.showLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '加载中...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }
    wx.request({
      url: app.apiUrl('/product/detail'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        id: id
      },
      success: function (res) {
        let picsTemp = []
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showModal({
            title: '提示',
            content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          for (var i = 0; i < res.data.data.album.length; i++) {
            picsTemp.push(app.globalData.imgUrl + res.data.data.album[i].savepath + res.data.data.album[i].savename)
          }
          res.data.data.pics = picsTemp

          res.data.data.pic = app.globalData.imgUrl + res.data.data.file.savepath + res.data.data.file.savename

          // res.data.data.store = 10        //test
          res.data.data.collected = (res.data.data.collected == 0 ? false : true)
          res.data.data.price = res.data.data.price.toFixed(2)
          res.data.data.old_price = res.data.data.old_price.toFixed(2)

          let commentList = res.data.data.commentList

          for (var i = 0; i < commentList.length; i++) {
            commentList[i].avatar_url = app.globalData.imgUrl + commentList[i].user.avater.savepath + commentList[i].user.avater.savename
            commentList[i].creation_time = formatTime.formatDate(new Date(formatTime.getDateDiff(commentList[i].created_at)))
            for (var j = 0; j < commentList[i].product_comment_file.length; j++) {
              commentList[i].product_comment_file[j].url = app.globalData.imgUrl + commentList[i].product_comment_file[j].file.savepath + commentList[i].product_comment_file[j].file.savename
            }
          }

          console.log(commentList)

          that.setData({
            goodsDetail: res.data.data,
            selectSizePrice: res.data.data.price,
            selectSizePriceOld: res.data.data.old_price,
            buyNumMax: 100,
            buyNumber: (res.data.data.store > 0) ? 1 : 1,
            commentList: commentList,
            commentListFilter: commentList.slice(0, 4),
            commentPercent: res.data.data.feedback_rate,
            commentTotal: res.data.data.commentCount,
            introduction: res.data.data.detail,
            type: res.data.data.isSeckill,
            ifSecKill: res.data.data.isSeckill == 1? true : false,
            time: res.data.data.isSeckill == 1 ? res.data.data.seckill_end : "",
          })

          if (res.data.data.isSeckill == 1) {

            that.data.interval = setInterval(function () {
              let date = new Date(formatTime.formatTime(new Date(that.data.time)))
              let restTimeTemp = formatTime.restTime(new Date(), date)
            
              if (restTimeTemp.day == 0 && restTimeTemp.hour == 0 && restTimeTemp.minute && restTimeTemp.second) {
                that.getDetails(that.data.id)
              }
              //console.log(restTime)
              that.setData({
                restTime: restTimeTemp
              })

            }, 1000)

          }

          WxParse.wxParse('article', 'html', res.data.data.detail, that)
    
        }
        
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      },
      complete: function (res) {
        if (wx.showLoading)
          wx.hideLoading()
        else
          wx.hideToast()
      }
    })
  },

  /**
  * 获取购物车数量
  */
  getCartNum: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/cart/count'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        
      },
      success: function (res) {
        console.log("getcartnum")
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          // wx.showToast({
          //   title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
          //   icon: 'none',
          //   duration: 2000
          // })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          // res.data.data.count = 100
          that.setData({
            shopNum: res.data.data.count <= 99 ? res.data.data.count+"" : '99+'
          })
        }
       
      },
      fail: function (res) {
        // wx.showModal({
        //   title: '提示',
        //   content: '网络请求异常',
        //   showCancel: false
        // })
      },
      complete: function (res) {
       
      }
    })
  },

  /**
   * 向服务器添加购物车
   */
  addToCart: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/cart/add'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        goods_id: that.data.goodsDetail.id,
        number: that.data.buyNumber,
        ids: that.data.ids
      },
      success: function (res) {
        console.log(res.data)
        that.getCartNum()
        wx.showToast({
          title: '加入购物车成功',
          icon: 'success',
          duration: 2000
        })
        that.closePopupTap();
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
      }
    })
  },

  /**
   * 关注/取消关注
   */
  collectTap: function () {
    if (this.data.goodsDetail.collected) 
      this.removeCollectTap()
    else 
      this.addCollectTap()
  },

  /**
   * 关注商品
   */
  addCollectTap: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/user/addcollect'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        product_id: that.data.goodsDetail.id
      },
      success: function (res) {
        console.log('addcollect')
        console.log(res.data)
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.data,
            icon: 'none',
            duration: 2000
          })
        }
        
        let goodsDetailTemp = that.data.goodsDetail
        goodsDetailTemp.collected = true
        that.setData({
          goodsDetail: goodsDetailTemp
        })

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 取消关注商品
   */
  removeCollectTap: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/user/delcollect'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        product_id: that.data.goodsDetail.id
      },
      success: function (res) {
        console.log('removecollect')
        console.log(res.data)
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.data,
            icon: 'none',
            duration: 2000
          })
        }

        let goodsDetailTemp = that.data.goodsDetail
        goodsDetailTemp.collected = false
        that.setData({
          goodsDetail: goodsDetailTemp
        })

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  toAllComments: function () {
    wx.navigateTo({
      url: "/pages/comment-list/index?id=" + this.data.goodsDetail.id
    })
  },

  goShare: function () {
    
    app.shareMessage()
  }
})
